<template>
  <div>
    <div class="search">
      <input type="text" v-model='keywords' placeholder="输入城市名或拼音" class="search_input">
    </div>
    <div class="search-content" v-show="keywords" ref="cityList">
        <ul>
          <li class="search-item" v-for="item in list" :key="item.id">{{item.name}}</li>
          <li class="search-item" v-show="hasNoData">没有匹配到数据</li>
        </ul>
    </div>
  </div>
</template>
<script>
  //引入better-scroll插件
    import Bscroll from 'better-scroll'
    export default {
        name: "Search",
         props:{//接受城市数据
             cities:Object
         },
         data () {
            return {
               keywords:'',
               list:[],//定义城市数组
               timer:null
            }
         },
        computed:{
          hasNoData (){
            return !this.list.length;//当list没有数据的时候
          }
        },
        watch : {//监听
          keywords () {//搜索关键字
               if(this.timer){
                  clearTimeout(this.timer)
               }
               
               this.timer=setTimeout(()=>{//函数截留
                    const result=[];
                    for(let i in this.cities){
                        this.cities[i].forEach((value)=>{
                        //  查找关键字
                          if(value.spell.indexOf(this.keywords)>-1 || value.name.indexOf(this.keywords)>-1 ){
                            result.push(value);
                          }
                        })
                    }
                    this.list=result;//存入数据在list中
               },20)

          }
        },
       mounted () {
          this.scroll=new Bscroll(this.$refs.cityList);//实现搜索的城市列表滚动
       }
    }
</script>
<style scoped lang="stylus">
  .search{
    height:.36rem;
    background :#00bcd4;
    padding:0 .1rem;
    .search_input{
      width:100%;
      box-sizing:border-box;
      height:.31rem;
      line-height .31rem
      border-radius:.06rem;
      padding:0 .1rem
      text-align center
      color:#666
    }
  }
  .search-content{
      overflow:hidden;
      width: 100%
      position:absolute;
      top:.76rem;
      left:0;
      bottom:0;
      background :gainsboro;
      z-index:1;
     .search-item{
        line-height:.28rem;
        border-bottom:1px solid #cacaca;
        background-color:white;
        padding-left:.1rem;
     }
  }
</style>
